var dayMap={1:"周一",2:"周二",3:"周三",4:"周四",5:"周五",6:"周六",0:"周日"};
var datepicker_op={
    format: "yyyy-mm-dd",
    clearBtn: false,
    language: "zh-CN",
    autoclose: true,
    todayHighlight: true,
    minViewMode:0,
    orientation: "top left"
};

/* 字符串转日期对象 */
function getDate(yyyymmdd){
    if(yyyymmdd.length==10){        //yyyy-MM-dd
        return Date.parse(yyyymmdd.substr(0,4)+'/'+yyyymmdd.substr(5,2)+'/'+yyyymmdd.substr(8,2));
    }else if(yyyymmdd.length==8){   //yyyyMMdd
        return Date.parse(yyyymmdd.substr(0,4)+'/'+yyyymmdd.substr(4,2)+'/'+yyyymmdd.substr(6,2));
    }else if(yyyymmdd.length==6){    //yyyyMM
        return Date.parse(yyyymmdd.substr(0,4)+'/'+yyyymmdd.substr(4,2));
    }
}

//获取星期几 dayDate 的格式为 yyyy-MM-dd或者yyyymmdd
function getWeekDay(dayDate){
    var jsDate = new Date(Date.parse(dayDate.replace(/\-/g,'/')));
    var weekNumber = jsDate.getDay();
    return dayMap[weekNumber];
}

function setDatePicker(ec,dateGrp,input){
    if('week'==dateGrp){
    }else if('month'==dateGrp){
        datepicker_op.minViewMode=1;
        datepicker_op.format='yyyymm';
    }else{
        datepicker_op.minViewMode=0; 
        datepicker_op.format='yyyy-mm-dd';
    }
    input.datepicker('remove');
    input.datepicker(datepicker_op);
    //获取显示的日期数组
    var days_show=ec.getShowDays();
    var days_all=ec.getAllDays();
    //设置时间可选范围
    input.datepicker('setStartDate',new Date(getDate(days_all[0])));
    input.datepicker('setEndDate',new Date(getDate(days_all[days_all.length-days_show.length])));
}

//格式化输出数字
function format_number(n){
    var b=parseInt(n).toString(); 
    var len=b.length; 
    if(len<=3){return b;} 
    var r=len%3; 
    return r>0?b.slice(0,r)+","+b.slice(r,len).match(/\d{3}/g).join(","):b.slice(r,len).match(/\d{3}/g).join(","); 
};

//加百分号和样式
function getRate(floatNum){
     var s=parseFloat(floatNum).toFixed(1)+"%";
     if(floatNum > 0){
        return '<td class="text-danger">' + s + '<i class="upi"></i></td>';
     }else if(floatNum < 0){
         return '<td class="text-success">' + s + '<i class="downi"></i></td>';
     }else{
        return '<td>' + s + '</td>';
     }
}  

//格式化输出数字
function formatNum(n){
    if(n.toString().indexOf(".")>=0){
        return  n.toFixed(2);
    }else{
        return n;
    }
};        

//字符串转数字
function toNum(n){
    var num = new Number(n);
    return num.valueOf();
};


function isDom(obj) {
    return obj && obj.nodeType === 1 && typeof obj.nodeName == 'string';
}
var objToString = Object.prototype.toString;

function mergeItem(target, source, key, overwrite) {
    if (source.hasOwnProperty(key)) {
        var targetProp = target[key];
        if (typeof targetProp == 'object' && !BUILTIN_OBJECT[objToString.call(targetProp)] && !isDom(targetProp)) {
            merge(target[key], source[key], overwrite);
        } else if (overwrite || !(key in target)) {
            target[key] = source[key];
        }
    }
}

function merge(target, source, overwrite) {
    for (var i in source) {
        mergeItem(target, source, i, overwrite);
    }
    return target;
}

function clone(source) {
    if (typeof source == 'object' && source !== null) {
        var result = source;
        if (source instanceof Array) {
            result = [];
            for (var i = 0, len = source.length; i < len; i++) {
                result[i] = clone(source[i]);
            }
        } else if (!BUILTIN_OBJECT[objToString.call(source)] && !isDom(source)) {
            result = {};
            for (var key in source) {
                if (source.hasOwnProperty(key)) {
                    result[key] = clone(source[key]);
                }
            }
        }
        return result;
    }
    return source;
}

function addCommas(x) {
    if (isNaN(x)) {
        return '-';
    }
    x = (x + '').split('.');
    return x[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g, '$1,') + (x.length > 1 ? '.' + x[1] : '');
}

 
var monthPattern=/^(\d{4})-?(\d{2})$/;
function formatShowDate(yyyymmdd){
    var rs = monthPattern.exec(yyyymmdd);
    if(rs){        
        return rs[1]+"年"+rs[2]+"月";
    }
    return yyyymmdd;
}

function isDay(domID){
    var statType = $('#'+domID).attr('statType');
    if('day'==statType){
        return true;
    }
    return false;
}

function isWeek(domID){
    var statType = $('#'+domID).attr('statType');
    if('week'==statType){
        return true;
    }
    return false;
}

function isMonth(domID){
    var statType = $('#'+domID).attr('statType');
    if('month'==statType){
        return true;
    }
    return false;
}

   //提示框
    function  tooltipFunc(params, ticket, callback,echarts_option, domID){
        var dateVal = formatShowDate(params[0].name);
        var curOption = echarts_option;
        var index_current=getIndexByName(curOption.xAxis[0].data,params[0].name);

        var result='<table class="table-center">';
        result+='<tr><td>'+dateVal+'</td><td>';
        var isStatDay = isDay(domID); 
        if(isStatDay)
            result += getWeekDay(dateVal);
        result += '</td>';
        result += '</td><td>占比</td>';
        if(isStatDay)
            result +="<td>日环比</td><td>周同比</td>";
        else if(isWeek(domID))
            result += "<td>周环比</td>";
         else if(isMonth(domID))
            result += "<td>月环比</td>";
        result += '</tr>';

        var total=0;

        $(params).each(function(index,para){
            total+=para.data;
        });

        $(params).each(function(index,para){
            var s=((para.data/total)*100).toFixed(2);
            result+='<tr><td>'+para.seriesName+'</td><td>'+addCommas(para.data)+'</td><td>'+s+'%</td>';

            var seriesIndex = para.seriesIndex;
            var day_td="<td>--</td>";
            //日周月 环比(前一日周月)
            if(index_current-1>=0){
                var data_yesday = null;
                data_yesday= curOption.series[seriesIndex].data[index_current-1];
                if(data_yesday != null){
                    var s=(((para.data/data_yesday)-1)*100).toFixed(2);
                    if(s>0){
                        day_td='<td style="color: orangered;">'+s+'%&#8593</td>';
                    }else{
                        day_td='<td style="color: greenyellow;">'+s+'%&#8595</td>';
                    }
                }
            }
            result += day_td;
            //周同比(日)
            if(isStatDay){
                var week_td='<td>--</td>';
                if(index_current-7>=0){
                    data_week= curOption.series[seriesIndex].data[index_current-7];
                    var s=(((para.data/data_week)-1)*100).toFixed(2);
                    if(s>0){
                        week_td='<td style="color: orangered;">'+s+'%&#8593</td>';
                    }else{
                        week_td='<td style="color: greenyellow;">'+s+'%&#8595</td>';
                    }
                }
                result += week_td;
            }
            result += '</tr>';
        });
        result+='</table>';
        return result;
    }

function setCompareTooltip(copy,domID){
    copy.series[1]&&copy.series[1].tooltip&&(copy.series[1].tooltip={show:false});
    copy.series[2]&&copy.series[2].tooltip&&(copy.series[2].tooltip={show:false});
    copy.series[3]&&copy.series[3].tooltip&&(copy.series[3].tooltip={show:false});

    copy.tooltip.formatter=function(params, ticket, callback){
        var date_current=params[0][1];
        var data_current=params[0][2];
        var index_current=getIndexByName(copy.xAxis[0].data,date_current);

        var dateVal = formatShowDate(date_current);
        var result='<table class="table-center">' +
            '<tr><td>'+dateVal;
        //是日要显示周几
        if(isDay(domID))
             result += ' ('+getWeekDay(dateVal)+')';
        result += '</td><td>'+addCommas(data_current)+'</td></tr>';
        if(copy.series[1]){
            var data_compare=copy.series[1].data[index_current];
            var s=(((data_current-data_compare)/data_compare)*100).toFixed(2);
            dateVal = formatShowDate(copy.xAxis[1].data[index_current]);
            result+='<tr><td>'+dateVal;
            if(isDay(domID))
                result += ' ('+getWeekDay(dateVal)+')';
            result += '</td><td>'+addCommas(data_compare)+'</td></tr>';
            if(s>0){
                result+='<tr><td>变化</td><td style="color: orangered">'+s+'%&#8593</td></tr>';
            }else{
                result+='<tr><td>变化</td><td style="color: greenyellow">'+s+'%&#8595</td></tr>';
            }
        }
        result+='</table>';
        return   result;
    }
}

function setCompareLegend(copy){
    copy.legend.data=[copy.series[0].name, copy.series[1].name];
    copy.legend.selectedMode=false;
}

function  setCompareSeries(option_day,copy,index,index_time,index_show,length){
    copy.series=[];
    //原来数据
    copy.series.push(clone(option_day.series[index]));
    copy.series[0].type='line';
    copy.series[0].data=option_day.series[index].data.slice(index_show,index_show+length);
    delete  copy.series[0].stack;
    delete  copy.series[0].itemStyle;
    //对比数据
    copy.series.push(clone(option_day.series[index]));
    copy.series[1].type='line';
    copy.series[1].name="对比时间段";
    copy.series[1].xAxisIndex=1;
    delete  copy.series[1].stack;
    delete  copy.series[1].itemStyle;

    copy.series[1].data=option_day.series[index].data.slice(index_time,index_time+length);
    if(length>31){return}
    //对比柱
    copy.series.push({
        tooltip:{show:false},
        show:false,
        name: '对比时间段1',
        type: 'bar',
        stack: '1',
        barWidth:3,
        xAxisIndex:1,
        itemStyle:{
            normal:{
                color:'rgba(0,0,0,0)'
            },
            emphasis:{
                color:'rgba(0,0,0,0)'
            }
        },
        data: function(){
            var i=0;
            return $.map(copy.series[1].data,function(val){
                var tt=copy.series[0].data[i++];
                if(toNum(val)<toNum(tt)){
                    return val;
                }else{
                    return tt;
                }
            })
        }()
    });
    copy.series.push({
        tooltip:{show:false},
        name: '变化',
        type: 'bar',
        stack: '1',
        xAxisIndex:1,
        data: function(){
            var i=0;
            return $.map(copy.series[1].data,function(val){
                var tt=copy.series[0].data[i++];
                if(toNum(val)<toNum(tt)){
                    return tt-val;
                }else{
                    return {value : val-tt, itemStyle:{ normal:{color:'red'}}};
                    //return val-tt;
                }
            })
        }()
    });
}

function setCompareXaxis(option_day,copy,index_time,index_show,length){
    copy.xAxis=[];
    copy.xAxis.push(clone(option_day.xAxis[0]));
    copy.xAxis.push(clone(option_day.xAxis[0]));
    copy.xAxis[0].data=option_day.xAxis[0].data.slice(index_show,index_show+length);
    copy.xAxis[1].data=option_day.xAxis[0].data.slice(index_time,index_time+length);
}

function getIndexByName(data,name) {
    var dataLength = data.length;
    for (var i = 0; i < dataLength; i++) {
        if (data[i] == name || typeof data[i].value != 'undefined' && data[i].value == name) {
            return i;
        }
    }
    return -1;
}

function formatTime(time){
    return time;
}


var BUILTIN_OBJECT = {
    '[object Function]': 1,
    '[object RegExp]': 1,
    '[object Date]': 1,
    '[object Error]': 1,
    '[object CanvasGradient]': 1
};


function twoLineChart(chart1,option1, chart2,option2, option_dom_id){
    this.myChart1 = chart1;
    this.myChart2 = chart2;
    this.option_1 = option1;
    this.option_2 = option2;
    this.option_dom_id = option_dom_id;
    var xAxis_show;     // X轴所显示的时间区间
    var legend_SelectedMap={};  //需要记忆图例的选择状态
    //添加对比--图一
    this.addCompare_1 = function(time){
        var option_1 = this.option_1;
        time=formatTime(time);        
        var copy=clone(this.option_1);
        copy.toolbox.feature.magicType.show=false;
        copy.toolbox.feature.dataZoom.show=false;
        var index_time=getIndexByName(this.option_1.xAxis[0].data,time);
        var index_show=getIndexByName(this.option_1.xAxis[0].data,this.getShowDays()[0]);
        var length=this.getShowDays().length;
        setCompareXaxis(this.option_1,copy,index_time,index_show,length);
        var index=0;
        //选中对比时，再次选择指标，需要记忆图例的选择状态
        $.each(legend_SelectedMap,function(key,value){
            //判断是否在当前图例值中，应为echarts会把"对比时间段"也放入SelectedMap
            if($.inArray(key,option_1.legend.data) != -1){
                if(value){
                    return false;
                }
                index++;
            }     
        });
        // console.log(index);
        if(index<3){
            setCompareSeries(this.option_1,copy,index,index_time,index_show,length);
            setCompareLegend(copy);
            setCompareTooltip(copy,this.option_dom_id);
            delete copy.dataZoom;
            this.myChart1.restore();
            this.myChart1.setOption(copy,true);
        }

    }

    //添加对比--图二
    this.addCompare_2 = function(time){
        var option_2 = this.option_2;
        time=formatTime(time);
        var copy=clone(this.option_2);
        copy.toolbox.feature.magicType.show=false;
        copy.toolbox.feature.dataZoom.show=false;
        var index_time=getIndexByName(this.option_2.xAxis[0].data,time);
        var index_show=getIndexByName(this.option_2.xAxis[0].data,this.getShowDays()[0]);
        var length=this.getShowDays().length;
        setCompareXaxis(this.option_2, copy,index_time,index_show,length);
        var index=0;
        //选中对比时，再次选择指标，需要记忆图例的选择状态
        $.each(legend_SelectedMap,function(key,value){
            //判断是否在当前图例值中，应为echarts会把"对比时间段"也放入SelectedMap
            if($.inArray(key,option_2.legend.data) != -1){
                if(value){
                    return false;
                }
                index++;
            }     
        });
        // console.log(index);
        if(index<3){
            setCompareSeries(this.option_2, copy,index,index_time,index_show,length);
            setCompareLegend(copy);
            setCompareTooltip(copy,this.option_dom_id);
            delete copy.dataZoom;
            this.myChart2.restore();
            this.myChart2.setOption(copy,true);
        }

    }

    this.hideDataZoom = function(){
        var legend_SelectedMap_1=clone(this.myChart1.component.legend.getSelectedMap());
        var legend_SelectedMap_2=clone(this.myChart2.component.legend.getSelectedMap());
        legend_SelectedMap = merge(legend_SelectedMap_1, legend_SelectedMap_2, true);
        xAxis_show=clone(this.myChart2.component.dataZoom.option.xAxis[0].data);    //记忆缩放
        this.option_2.dataZoom.show=false;

        this.myChart1.setOption(this.option_1,false);
        this.myChart2.setOption(this.option_2,false);
    }

    //设置缩放区间
   this.setDataZoom = function(startDate,endDate) {
        var xAxisLength = this.option_2.xAxis[0].data.length;
        var index_start=getIndexByName(this.option_2.xAxis[0].data,startDate);
        var index_end=getIndexByName(this.option_2.xAxis[0].data,endDate) + 1;
        var zoomRange = {start:index_start/xAxisLength*100, end: index_end/xAxisLength*100};
        this.myChart2.component.dataZoom.absoluteZoom(zoomRange);
    }

    //取消对比
   this.removeCompare =  function(){
        //恢复缩放
         var myChart1 = this.myChart1;
         var myChart2 = this.myChart2;
         var option_1 = this.option_1;
         var option_2 = this.option_2;
        this.option_2.dataZoom.show=true;
        //恢复图例的选择状态
        $.each(legend_SelectedMap,function(key,value){
            if($.inArray(key,option_1.legend.data) != -1){
               myChart1.component.legend.setSelected(key,value);
            }else if($.inArray(key,option_2.legend.data) != -1){
                myChart2.component.legend.setSelected(key,value);
            }else{
                myChart1.component.legend.setSelected(key,false);
                myChart2.component.legend.setSelected(key,false);
            }
        });

        this.setDataZoom(xAxis_show[0], xAxis_show[xAxis_show.length-1]);
        this.myChart1.setOption(this.option_1,true);
        this.myChart2.setOption(this.option_2,true);
    }


    this.getShowDays =  function(){
        return xAxis_show;
    }

    this.getAllDays =  function(){
        return this.option_2.xAxis.data||this.option_2.xAxis[0].data;
    }

}